﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects.DataClasses;
using System.Web.Mvc;
using Ovvio.Business;
using System.Data.Objects;
using System.ComponentModel.DataAnnotations;

namespace Ovvio.Web.Core
{
    [Serializable()]
    public class BaseModel<TEntity> 
        where TEntity : EntityObject, new()
    {
        private TEntity _entity;

        [ScaffoldColumn(false)]
        internal TEntity Entity
        {
            get
            {
                if (_entity == null)
                    _entity = new TEntity();
               return _entity;
            }
            set
            {
                _entity = value;
                OnEntityChanged(_entity);
            }
        }

        protected virtual void OnEntityChanged(TEntity entity)
        { }

        public SelectList CreateList<TEntity, TObjectContext>(string dataValueField, string dataTextField, Func<TEntity, bool> selectedPredicate)
            where TEntity : EntityObject, new()
            where TObjectContext : ObjectContext, new()
        {
            var service = new ServiceList<TEntity, TObjectContext>();
            var entities = service.GetEntities();
            TEntity selected = null;
            if (selectedPredicate != null)
            {
                var query = entities.Where(selectedPredicate);
                if (query.Any())
                    selected = query.First();
            }
            var list = new SelectList(entities, dataValueField, dataTextField, selected);

            return list;
        }


        public static List<TModel> CreateList<TModel, TEntity, TObjectContext>()
            where TEntity : EntityObject, new()
            where TObjectContext : ObjectContext, new()
            where TModel : BaseModel<TEntity>, new()
        {
            var service = new ServiceList<TEntity, TObjectContext>();
            var entities = service.GetEntities();
            var list = new List<TModel>();
            foreach (var e in entities)
                list.Add(new TModel() { Entity = e });
            return list;
        }


    }
}
